// Modal adpater for AJAX loading modal

'use strict';

//$("form").keypress(function(e) {
//  if (e.which == 13) {
//    return false;
//  }
//});

Date.prototype.yyyymmdd = function(split) {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();
  
  if(split) {
    return [this.getFullYear(),
            (mm>9 ? '' : '0') + mm,
            (dd>9 ? '' : '0') + dd
           ].join(split);
  } else {
    return [this.getFullYear(),
            (mm>9 ? '' : '0') + mm,
            (dd>9 ? '' : '0') + dd
           ].join('');
  }
};

$(document).on('change', "#uploadBtn", function(e){
  console.log($(this).parents(".input-group").find("#uploadFile"));
  $(this).parents(".input-group").find("#uploadFile")[0].value = this.value;
})

$(document).on('change', ".file-container input[type='file']", function(e) {
  $(this).parents(".file-container").find("span").html(this.value);
})

// modal trigger
$(document).on('click', '[data-toggle="modal"]', function (e) {
  
  e.preventDefault();
  var $this = $(e.currentTarget),
      url = $this.attr('href');
  
  if(url.indexOf('#') !== 0 && url !== 'javascript:void(0);'){
    var id = $this.attr('data-target').slice(1);
    var params = $this.attr('data-form-params');
    var data = params ? $('#' + params).serialize() : {};
    
    $.get(url, data, function (data) {
      $('<div class="modal fade" id="' + id + '" role="dialog" aria-hidden="true">' + data + '</div>').modal().on('hidden.bs.modal', function (e) {
        return $(e.currentTarget).remove();
      }).on('shown.bs.modal', function () {
        $this.trigger('shown.modal');
        return $this.off('click.bs.modal.data-api');
      });
    });
  }
});

$(document).on('click', '.paging-jump .go-btn', function (e) {
  
  var $input = $(this).parent().find("input");
  
  if($input.val() > $input.data("total")  || $input.val() == null || $input.val().trim() == '') {
    $input.val("");
    return false;
  }
  
  var url = $input.data("url") + ((($input.data("querystring") === undefined || $input.data("querystring") === '')) ? '' : $input.data("querystring"))
                               + ($input.data("filter") === undefined ? '' : '&filter=true')
                               + (($input.data("querystring") === undefined || $input.data("querystring") === '') ? '?page=' : '&page=')
                               + $input.val();
  window.location.href=url;
})


// tab lazy loading
$.fn.tabLazyLoading = function(url) {
  var $tab = $(this);
  $.get(url).done(function(data) {
    $($tab.data('target')).empty().append(data);
    $tab.data('loaded', 'true');
  }).fail(function() {
    if(!$($tab.data('target')).find('.loading-error').length)
    $($tab.data('target')).append('<p class="text-danger loading-error">网络异常，请稍后重新加载...</p>');
  });
}

function initMenu() {

  var activeSubmenu = $(".ihg-sidemenu").find('li.active');

  if(activeSubmenu.length > 0) {
    var parentFolder = $(activeSubmenu[0]).parents('.presentation');
    $(parentFolder).addClass('open');
    $(parentFolder).children('.subnav').addClass('open');

    $('.ihg-sidemenu').animate({
        scrollTop: $(activeSubmenu[0]).offset().top
    }, 500);
  }
}

function clearAllMenu() {
  $('.ihg-sidemenu').find('li').removeClass('open').removeClass('active');
  $('.ihg-sidemenu').find('.subnav').removeClass('open');
}

initMenu();

$('.ihg-sidemenu li a').on('click', function(event) {
    
  if($(this).parent().hasClass('presentation')) {
    
    $(this).parent().toggleClass('open');
    $(this).parent().children('.subnav').toggleClass('open');

  } else if(!$(this).parent().hasClass('presentation') && !$(this).parent().hasClass('active')){

    clearAllMenu();
    $(this).parent().addClass('active');
    initMenu();

  }

});


/* i18n switch operate */
$('.ihg-navbar-nav .btn-i18n').on('click', function() {
  
  var href = window.location.href;
  var locale = $(this).data('locale');
  
  var targetHref = changeUrlArg(href, 'locale', locale);
  window.location.href = targetHref;
  
});

function changeUrlArg(url, arg, val){
  var pattern = arg+'=([^&]*)';
  var replaceText = arg+'='+val;
  return url.match(pattern) ? url.replace(eval('/('+ arg+'=)([^&]*)/gi'), replaceText) : (url.match('[\?]') ? url+'&'+replaceText : url+'?'+replaceText);
}